package com.yunshu.yunshuapp.user;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sina.weibo.sdk.utils.LogUtil;
import com.yunshu.yunshuapp.Deserializable;
import com.yunshu.yunshuapp.network.YSCallback;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.utils.YSUtils;

import java.io.IOException;
import java.util.HashMap;


/**
 * Created by zhouwenjie on 2016/12/29.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class YSUser implements Deserializable {

    private static final int MODE_PRIVATE = 0;
    private static Context contenxt;

    private boolean isLogin;

    private String phone;
    private String nickname;
    @JsonProperty("id")
    private String uid;
    @JsonIgnore
    private String password;

    @JsonProperty("icon")
    private String avatarUrl;

//    @JsonIgnoreProperties
//    private Image avatarImg;

    @JsonIgnoreProperties
    private String name;

    private String qq;
    private String wx;
    private String company;

    private String position;
    private String email;
    private String birthday;

    private String bpushChannelId;
//    public String bpushUserId;

    @JsonProperty("channels")
    private String kuaixunChannels;

    @JsonProperty("contacts")
    private Short contacts = 0;

    private String mainbusiness;

    /**
     * 0:未设置 1：男 2：女
     */
    private int sex;

    @JsonIgnore
    private String token;

    private volatile static YSUser _user;

    public YSUser() {
        isLogin = false;
    }

    public static YSUser instance() {
        if (_user == null) {
            synchronized (YSUser.class) {
                if (_user == null) {
                    _user = new YSUser();
                }
            }
        }

        return _user;
    }

    private volatile static String _tempChannel;
    public static void setXiaoMiPushChannel(String channel){
        _tempChannel = channel;
        YSUser.updateXiaoMiChannelId();
    }

    public static void setGetuiPushChannel(String channel){
        _tempChannel = channel;
        YSUser.updateGetuiChannelId();
    }

    public static void initUser(Context ctx) {

        contenxt = ctx;
        //获取SharedPreferences对象
        SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
        String token = sp.getString("000001", "none");
        String jsonStr = sp.getString("xxxx2kk", "none");
        if (token != null && token.length() > 0 && !token.equals("none")) {
            YSUser.instance().token = token;
            ObjectMapper mapper = new ObjectMapper();
            try {
                YSUser newUser = mapper.readValue(jsonStr, YSUser.class);
                YSUser.instance().copyFrom(newUser);
                YSUser.instance().isLogin = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void copyFrom(YSUser newUser) {
        if (newUser == null ) return;
        this.phone = newUser.phone;
        this.nickname = newUser.nickname;
        this.setUid(newUser.getUid());
        this.password = newUser.password;

        this.avatarUrl = newUser.avatarUrl;

//    @JsonIgnoreProperties
//    private Image avatarImg;

        this.name = newUser.name;
        this.qq = newUser.qq;
        this.wx = newUser.wx;
        this.company = newUser.company;

        this.position = newUser.position;
        this.email = newUser.email;
        this.birthday = newUser.birthday;
        this.kuaixunChannels = newUser.kuaixunChannels;
        this.contacts = newUser.contacts;
    }


    private void saveToken(String token) {
        //获取SharedPreferences对象
        SharedPreferences sp = contenxt.getSharedPreferences("SP", MODE_PRIVATE);
        //存入数据
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("000001", token);
        editor.commit();
    }

    public static boolean isLogin() {
        return YSUser.instance().isLogin && YSUser.instance().getUid()!= null ;
    }


    public static void loginWithResult(JsonNode json) {

        YSUser user = YSUser.instance();
        user.deserialize(json);
        user.isLogin = true;
        SharedPreferences sp = contenxt.getSharedPreferences("SP", MODE_PRIVATE);
        //存入数据
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("xxxx2kk", json.toString());
        editor.commit();
    }

    public static void logout() {
        YSUser user = YSUser.instance();
        user.isLogin = false;
        SharedPreferences sp = contenxt.getSharedPreferences("SP", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("xxxx2kk", "");
        editor.putString("000001", "");
        editor.commit();

        user.setUid(null);
        user.avatarUrl = null;

        //        nickname
        user.phone = null;
        user.qq = null;
        user.wx = null;
        user.company = null;

        user.position = null;
        user.email = null;
        user.birthday = null;
        user.sex = 0;
        user.contacts = 0;
    }

    public String serialize() {
        ObjectMapper mapper = new ObjectMapper();
        String result = null;
        try {
            result = mapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public void deserialize(JsonNode json) {
        ObjectMapper mapper = new ObjectMapper();
        try {

            String jsonStr = json.toString();
            YSUser newUser = mapper.readValue(jsonStr, YSUser.class);
            YSUser.instance().copyFrom(newUser);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void persistent() {
        ObjectMapper mapper = new ObjectMapper();
        String result = null;
        try {
            result = mapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        SharedPreferences sp = contenxt.getSharedPreferences("SP", MODE_PRIVATE);
        //存入数据
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("xxxx2kk", result);
        editor.commit();
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        if (this.token != null && this.token.equals(token)) {
            return;
        }
        this.token = token;
        this.saveToken(token);
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getAvatarUrl() {
        return avatarUrl;
    }

    public void setAvatarUrl(String avatarUrl) {
        this.avatarUrl = avatarUrl;
    }

//    public Image getAvatarImg() {
//        return avatarImg;
//    }
//
//    public void setAvatarImg(Image avatarImg) {
//        this.avatarImg = avatarImg;
//    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getQq() {
        return qq;
    }

    public void setQq(String qq) {
        this.qq = qq;
    }

    public String getWx() {
        return wx;
    }

    public void setWx(String wx) {
        this.wx = wx;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String mail) {
        this.email = mail;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public void setKuaixunChannels(String channels) {
        kuaixunChannels = channels;
    }

    public String getKuaixunChannels() {
        return kuaixunChannels;
    }

    public void update(YSCallback callback, Activity activity) {
        this.updateOnActivity(activity, callback);
    }

    public void updateOnActivity(final Activity activity, final YSCallback callback) {
        if (_tempChannel != null)
            this.setBpushChannelId(_tempChannel);
        String string = this.serialize();
        HashMap params = new HashMap();
        params.put("user", string);
        new YSRequest(activity).POST(YSRequest.UPDATE_USER, params, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                if(callback != null)
                    callback.onResponse(isSuccess,result);
                if (isSuccess == YSRequest.REQUEST_OK){
                    loginWithResult(result);
                }
            }
        });
    }

    public static void updateXiaoMiChannelId() {
        YSUser.updateChannelId("1");
    }

    public static void updateGetuiChannelId() {
        YSUser.updateChannelId("3");
    }
    public static void updateChannelId(String type){
        YSUser.instance().bpushChannelId = _tempChannel;

        new YSRequest(null).GET(YSRequest.PushChannelBind, "bpushChannelId="+ _tempChannel+"&id="+YSUser.instance().getUid()+"&pushType="+type, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {

            }
        });
    }

    public Short getContacts() {
        return contacts;
    }

    public void setContacts(Short contacts1) {
        contacts = contacts1;
    }

    public String getBpushChannelId() {
        return bpushChannelId;
    }

    public void setBpushChannelId(String bpushChannelId) {
        this.bpushChannelId = bpushChannelId;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
}
